/**
 * Created by moyu on 2017/4/7.
 */
// 监控文件变化
const path = require('path');
const fs = require('fs');
const cp = require('child_process');

const watcher = fs.watch(path.join(__dirname, 'backend'), {recursive: true});

watcher.on('change', (eventType, filename) => {
    console.log(eventType, filename);
    if(filename.startsWith('.') || (!filename.endsWith(".js") /*&& !filename.endsWith(".pug")*/) ) {
        return;
    }
    serverProcess.kill('SIGINT');
    serverProcess = run();
});

const run = () => {
    return cp.fork(path.join(__dirname, './backend/index.js'), process.argv, {stdio: [0, 1, 2, 'ipc'], cwd: path.join(__dirname, 'backend')})
        .on('exit', code => {
            console.log('serverProcess exit with code', code);
            if (code !== 0 && code != null) {
                serverProcess.kill('SIGINT');
                serverProcess = run();
            }
        })
        .on('message', (message) => {
            console.log('Get Message from child: %s', message);
            if (message === 'bye') {
                serverProcess.kill('SIGINT');
                serverProcess = run();
            }
        })

}

let serverProcess = run();

